package com.ailiwu.www.ailiwu.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ailiwu.www.ailiwu.R;
import com.ailiwu.www.ailiwu.bean.GameAdInfo;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.ArrayList;
import java.util.List;

public class ScrollAdView extends FrameLayout implements OnPageChangeListener {

    private ArrayList<AdsBean> adsList = new ArrayList<AdsBean>();

    private Context context;
    private ViewPager mViewpager;

    private LinearLayout pointGroup;
    private TextView tvDescriptions;
    private List<ImageView> imageList = new ArrayList<ImageView>();
    private int lastPointIndex;
    private boolean isAutoRun = true;


    private int position;

    private ImageLoader imageLoader;

    private DisplayImageOptions options;

    public void setOnPageImageClickListener(OnPageImageClickListener listener) {
        this.listener = listener;
    }

    private OnPageImageClickListener listener;

    // 自动滚动的消息机制
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (isAutoRun) {
                mViewpager.setCurrentItem(mViewpager.getCurrentItem() + 1);
                handler.sendEmptyMessageDelayed(0, 4000);
            }
        }
    };

    private MyPagerAdapter mAdsAdapter;

    public ScrollAdView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    public ScrollAdView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public ScrollAdView(Context context) {
        super(context);
        initView(context);
    }

    // 初始化控件
    private void initView(Context context) {
        this.context = context;

        adsList.add(
                new AdsBean("", null));
        adsList.add(
                new AdsBean("", null));
        adsList.add(
                new AdsBean("", null));


        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(context));
        options = new DisplayImageOptions.Builder()
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .showImageOnLoading(R.color.write)
                .showImageForEmptyUri(R.color.write)
                .showImageOnFail(R.color.write)
//                .displayer(new FadeInBitmapDisplayer(100))//渐入的方式进入
                .cacheInMemory(false)
                .cacheOnDisk(true)
                .build();

        View.inflate(context, R.layout.scroll_ad_view, this);

        mViewpager = (ViewPager) findViewById(R.id.viewpager);
        pointGroup = (LinearLayout) findViewById(R.id.ll_image_point);

        tvDescriptions = (TextView) findViewById(R.id.tv_image_descri);
        tvDescriptions.setText(adsList.get(0).getTitle());// 设置第一个标题

        mAdsAdapter = new MyPagerAdapter();
        mViewpager.setAdapter(mAdsAdapter);


        initDatas();
        mViewpager.setOnPageChangeListener(this);
        handler.sendEmptyMessageDelayed(0, 4000);
//
    }

    // 转换为AdBean对象集合

    public void SetAdsBeanList(List<GameAdInfo> infos) {
        adsList.clear();
        pointGroup.removeAllViews();
        imageList.clear();
        if (infos != null) {
            for (int i = 0; i < infos.size(); i++) {
                String title = infos.get(i).getName();
                String image = infos.get(i).getImage();

                adsList.add(new AdsBean(title, image));
            }
            initDatas();

        }

    }

    // 初始化数据
    private void initDatas() {
        for (int i = 0; i < adsList.size(); i++) {
            // 添加数据到ImageView集合中
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ScaleType.CENTER_CROP);
            imageLoader.displayImage(adsList.get(i).getImagPath(), imageView, options);
            imageList.add(imageView);
            // 设置下面指示点的指示个数
            ImageView point = new ImageView(context);
            point.setBackgroundResource(R.drawable.selector_point);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 3, 15, 3);
            point.setLayoutParams(params);
            // 初始化指示器指向第一个point
            if (i == 0) {
                point.setEnabled(true);
            } else {
                point.setEnabled(false);
            }
            pointGroup.addView(point);
        }

        mAdsAdapter.notifyDataSetChanged();
        // 设置当前的item为一个无限循环的中间值
        mViewpager.setCurrentItem(10000/2-10000%imageList.size());
    }

    public interface OnPageImageClickListener{
        void OnPagerClick(int position,View view);
    }
    /**
     * ViewPager适配器
     */
    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return imageList == null ? 0 : 10000;// 伪无限制循环,将界面放置于一个很大的数额页码;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View v = imageList.get(position % imageList.size());
            if (v.getParent() != null) {
                ((ViewGroup) v.getParent()).removeView(v);
            }
            container.addView(v);
            v.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.OnPagerClick(position % imageList.size(), v);
                    }
                }
            });
            return v;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

//            if(adsList.size()>3){
//                 container.removeView((View) object);
//                 object = null;
//            }

        }
    }

    /*
     * pager监听器
     */
    // 当pager被切换之后 回调
    @Override
    public void onPageSelected(int position) {
        int a = position % imageList.size();
        // 设置标题的改变
        tvDescriptions.setText(adsList.get(a).getTitle());
        // 设置当前point的状态和前一个point的状态
        pointGroup.getChildAt(a).setEnabled(true);
        pointGroup.getChildAt(lastPointIndex).setEnabled(false);
        // 将当前的arg0赋值给lastPointIndex
        lastPointIndex = a;

    }

    // 状态改变时调用
    @Override
    public void onPageScrollStateChanged(int arg0) {
        switch (arg0) {
            case ViewPager.SCROLL_STATE_DRAGGING:
                isAutoRun = false;
                break;
            case ViewPager.SCROLL_STATE_IDLE:
                isAutoRun = true;
                if (!handler.hasMessages(0)) {
                    handler.sendEmptyMessageDelayed(0, 4000);
                }
                break;
            default:
                break;
        }
    }

    // 滚动时回调
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    // 对外的接口来设置图片和文字

    // 广告实体类
    class AdsBean {
        String title;
        String imagPath;

        public AdsBean() {
        }

        public AdsBean(String title, String imagPath) {
            this.title = title;
            this.imagPath = imagPath;
        }

        @Override
        public String toString() {
            return "adBean [title=" + title + ", imagPath=" + imagPath + "]";
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getImagPath() {
            return imagPath;
        }

        public void setImagPath(String imagPath) {
            this.imagPath = imagPath;
        }

    }

}
